<template>
  <div class="add-edit">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>会员管理</el-breadcrumb-item>
      <el-breadcrumb-item>
        {{addEditData.id?'编辑'+titleList[addEditData.type]+'活动':'新增'+titleList[addEditData.type]+'活动'}}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="easy-content">
      <el-form label-width="100px"
        :model="addEditData"
        :rules="rules"
        :disabled="isLook"
        ref="formRule">
        <div class="box">
          <h3>基本信息</h3>
          <el-form-item label="活动名称:"
            prop="name">
            <el-input placeholder="请输入名称"
              v-model="addEditData.name"
              style="width:300px"
              maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="生效时间:"
            prop="startEndTime"
            v-if="addEditData.type != 3">
            <el-date-picker v-model="addEditData.startEndTime"
              type="daterange"
              range-separator="至"
              value-format="yyyy-MM-dd"
              size="small"
              style="height:34px;"
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="生效时间:"
            prop="startEndTime"
            v-if="addEditData.type == 3">
            <span>时间范围&nbsp;&nbsp;</span>
            <el-date-picker v-model="addEditData.startEndTime"
              type="daterange"
              range-separator="至"
              value-format="yyyy-MM-dd"
              size="small"
              style="height:34px;"
              start-placeholder="开始日期"
              :picker-options="pickerOptions"
              end-placeholder="结束日期">
            </el-date-picker>
            <el-checkbox v-model="addEditData.userDay">会员日</el-checkbox>
            <el-checkbox v-model="addEditData.birthday">会员生日</el-checkbox>
          </el-form-item>
        </div>
        <div class="box"
          v-if="addEditData.type !=2">
          <h3>{{addEditData.type ==1?'开卡有礼':'参与规则'}}</h3>
          <el-form-item :label="addEditData.type ==1?'新开通卡等级':'参与对象'"
            prop="rules"
            style="margin-bottom:0px;">
            <el-checkbox :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange">所有会员卡等级</el-checkbox>
            <el-checkbox-group v-model="addEditData.rules"
              @change="handleCheckedCardsChange">
              <el-checkbox v-for="item in memberCardList"
                :label="item.id"
                :key="item.id">{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        <div class="box"
          v-if="addEditData.type==2">
          <h3>参与规则</h3>
          <el-form-item label="参与对象:"
            style="margin-bottom:0px;">
            <el-radio-group v-model="addEditData.obj"
              @change="setCardChecked">
              <el-radio v-for="item in memberCardList"
                :label="item.id"
                :key="item.id"
                v-if="item.num<memberCardList[memberCardList.length-1].num">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="升级到:"
            style="margin-bottom:0px;">
            <el-radio-group v-model="addEditData.upObj">
              <el-radio v-for="item in memberCardList"
                :label="item.id"
                :key="item.id"
                v-if="item.id>addEditData.obj">{{item.name}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="box"
          v-if="addEditData.type==3">
          <h3>消费策略</h3>
          <el-form-item label="赠送条件:"
            prop="consume"
            style="margin-bottom:0px;">
            <span>单次满&nbsp;&nbsp;</span>
            <el-input-number controls-position="right"
              v-model="addEditData.consume"
              :min="1"
              :max="1000"
              size="small"></el-input-number>
            <span>&nbsp;&nbsp;元</span>
          </el-form-item>
        </div>
        <div class="box">
          <h3>活动奖品</h3>
          <div class="clearfix box-1">
            <el-row :gutter="1">
              <el-col :span="2">
                <div class="name">
                  <el-checkbox v-model="addEditData.coupon">优惠券</el-checkbox>
                </div>
              </el-col>
              <el-col :span="20"
                v-if="addEditData.coupon">
                <el-button type="primary"
                  size="small"
                  v-if="!isLook"
                  @click="addCoupon">增添券</el-button>
                <el-table style="margin-top:10px"
                  max-height="550px"
                  :data="selectedCouponList">
                  <el-table-column label="券名称"
                    prop="name">
                  </el-table-column>
                  <el-table-column label="券类型"
                    prop="typeName">
                  </el-table-column>
                  <el-table-column label="状态"
                    prop="stateName">
                  </el-table-column>
                  <el-table-column label="有效期"
                    prop="indate">

                  </el-table-column>
                  <el-table-column label="发放数量">
                    <template slot-scope="scope">
                      <el-input-number controls-position="right"
                        v-model="scope.row.num"
                        :min="1"
                        :max="10000"
                        size="small"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button type="text"
                        @click="_delete(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </div>
          <div class="clearfix box-1">
            <el-row :gutter="1"
              v-if="addEditData.type!=3">
              <el-col :span="2">
                <div class="name">
                  <el-checkbox v-model="addEditData.integral">积分</el-checkbox>
                </div>
              </el-col>
              <el-col :span="20"
                v-if="addEditData.integral">
                <el-form-item label="赠送"
                  label-width="50px"
                  prop="integralNum">
                  <el-input-number controls-position="right"
                    v-model="addEditData.integralNum"
                    :min="1"
                    :max="1000"
                    size="small"></el-input-number>
                  <span>&nbsp;&nbsp;积分</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="1"
              v-if="addEditData.type ==3">
              <el-col :span="2">
                <div class="name">
                  <el-checkbox v-model="addEditData.integral">积分</el-checkbox>
                </div>
              </el-col>
              <el-col :span="20"
                v-if="addEditData.integral">
                <div>
                  <el-radio v-model="addEditData.integralDouble"
                    label="2">赠送积分金额</el-radio>
                  <el-form-item label="赠送"
                    v-if="addEditData.integralDouble==2"
                    prop="integralNum"
                    label-width="50px">
                    <el-input-number controls-position="right"
                      v-model="addEditData.integralNum"
                      :min="1"
                      :max="1000"
                      size="small"></el-input-number>
                    <span>&nbsp;&nbsp;积分</span>
                  </el-form-item>
                </div>
                <div>
                  <el-radio v-model="addEditData.integralDouble"
                    label="1">赠送积分倍数</el-radio>
                  <el-form-item label="赠送"
                    v-if="addEditData.integralDouble==1"
                    prop="integralNum"
                    label-width="50px">
                    <el-input-number controls-position="right"
                      v-model="addEditData.integralNum"
                      :min="1"
                      :max="1000"
                      size="small"></el-input-number>
                    <span>&nbsp;&nbsp;倍</span>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <el-dialog title="选择优惠券"
        :visible.sync="dialogVisible"
        width="1000px">
        <el-form>
          <div style="margin-bottom:10px">
            <el-dropdown @command="setType">
              <span class="el-dropdown-link">
                {{typeStr}}
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <!-- 1：代金券，2：折扣券，3：礼品券 -->
                <el-dropdown-item :command="{title:'全部类型',type:''}">全部类型</el-dropdown-item>
                <el-dropdown-item :command="{title:'代金券',type:'1'}">代金券</el-dropdown-item>
                <el-dropdown-item :command="{title:'折扣券',type:'2'}">折扣券</el-dropdown-item>
                <el-dropdown-item :command="{title:'礼品券',type:'3'}">礼品券</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div style="height:550px;overflow-y:auto;overflow-x:hidden">
            <table class="custom-1">
              <tr class="style">
                <th style="width:20px">
                  <el-checkbox v-model="isAllChecked"
                    @change="checkAllChange"></el-checkbox>
                </th>
                <th>
                  卷名称
                </th>
                <th>优惠券类型</th>
                <th>有效时间</th>
              </tr>
              <tr v-for="(item,index) in couponList"
                :key="index"
                v-show="type=='' || type == item.type">
                <td style="width:20px">
                  <el-checkbox v-model="item.check"
                    @change="checkChange"></el-checkbox>
                </td>
                <td @click="_checkChange(item)">
                  {{item.name}}
                </td>
                <td @click="_checkChange(item)">{{item.typeName}}</td>
                <td @click="_checkChange(item)">{{item.indate}}</td>
              </tr>
            </table>
          </div>

        </el-form>
        <span slot="footer"
          class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary"
            @click="couponSelectSure">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <InfomationBtns>
      <el-button type="primary"
        size="small"
        @click="$router.back()">{{!isLook?'取消':'返回'}}</el-button>
      <el-button type="primary"
        size="small"
        @click="sure('formRule')"
        v-if="!isLook">保存</el-button>
    </InfomationBtns>
  </div>
</template>

<script>
import InfomationBtns from "@/components/common/InfomationBtns";
import {
  addEditActive,
  getMemberCardList,
  getCouponList,
  getActiveInfo
} from "@/public/js/member";

import { PullOnlinePurchase } from "@/public/js/saleRoom";
export default {
  components: { InfomationBtns },
  props: {},
  data() {
    var checkDate = (rule, value, callback) => {
      if (!value || !value.length) {
        return callback(new Error("请选择生效时间"));
      }
      if (value[1] <= value[0]) {
        return callback(new Error("结束时间必须大于开始时间"));
      } else {
        callback();
      }
    };
    return {
      radio: "1",
      titleList: ["", "开卡有礼", "升级有礼", "消费有礼"],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      addEditData: {
        id: "",
        type: "",
        name: "",
        timeScope: 1,
        userDay: false,
        birthday: false,
        rules: [],
        obj: "",
        upObj: "",
        coupon: false,
        coupons: [],
        integral: false,
        integralDouble: "2",
        integralNum: undefined,
        consume: undefined,
        startEndTime: []
      },
      isLook: false,
      checkAll: false,
      memberCardList: [],
      isIndeterminate: false,
      couponList: [],
      dialogVisible: false,
      typeStr: "全部类型",
      type: "",
      pageNum: 1,
      multipleSelection: [],
      selectData: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      isAllChecked: false,
      selectedCouponList: [],

      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        startEndTime: [
          // {
          //   type: "array",
          //   required: true,
          //   message: "请选择生效时间",
          //   trigger: ["change", "blur"]
          // }
          { required: true, validator: checkDate, trigger: ["change", "blur"] }
        ],
        rules: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个等级",
            trigger: ["change", "blur"]
          }
        ],
        integralNum: [
          {
            required: true,
            message: "请输入积分金额/积分倍数",
            trigger: "blur"
          }
        ],
        consume: [
          { required: true, message: "请输入赠送条件金额", trigger: "blur" }
        ]
      }
    };
  },
  watch: {},
  computed: {},
  methods: {
    //获取优惠券列表
    _getCouponList() {
      PullOnlinePurchase({
        search: "",
        free: 1
      }).then(res => {
        let couponList = res.data.couponList;

        couponList.map(item => {
          item.num = 1;
          item.check = false;
        });
        this.couponList = couponList;
      });
    },
    //获取会员卡列表
    _getMemberCardList() {
      getMemberCardList().then(res => {
        this.memberCardList = res.data.memberCardList;
        this.memberCardList.forEach(item => {
          item.num = parseInt(item.num);
        });
        this.addEditData.obj = this.memberCardList[0].num;
        this.addEditData.upObj = this.memberCardList[1].num;
      });
    },
    handleCheckedCardsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.memberCardList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.memberCardList.length;
    },
    handleCheckAllChange(val) {
      let memberCardList = [];
      this.memberCardList.forEach(item => {
        memberCardList.push(item.id);
      });
      this.addEditData.rules = val ? memberCardList : [];

      this.isIndeterminate = false;
    },
    setCardChecked(val) {
      this.addEditData.upObj = this.memberCardList[val].id;
    },
    toggle() {
      let flag = true;
      this.couponList.forEach(item => {
        if (this.type == item.type || this.type == "") {
          if (!item.check) {
            flag = false;
          }
        }
      });
      this.isAllChecked = flag;
    },
    //单选
    checkChange(item) {
      this.toggle();
    },
    _checkChange(item) {
      item.check = !item.check;
      this.toggle();
    },
    checkAllChange(bollean) {
      this.isAllChecked = bollean;
      if (bollean) {
        this.couponList.forEach(item => {
          if (this.type == item.type || this.type == "") {
            item.check = true;
          }
        });
      } else {
        this.couponList.forEach(item => {
          if (this.type == item.type || this.type == "") {
            item.check = false;
          }
        });
      }
    },
    //增加优惠券
    addCoupon() {
      this.dialogVisible = true;
      this.selectData = [];
      let jy = {};
      this.selectedCouponList.forEach(_item => {
        this.selectData.push(_item.id);
        jy[_item.id] = _item.num;
      });
      this.couponList.map(item => {
        item.check = false;
        item.num = 1;
      });
      this.couponList.forEach(item => {
        if (this.selectData.indexOf(item.id) > -1) {
          item.check = true;
          item.num = jy[item.id];
        }
        this.toggle();
      });
    },
    //删除
    _delete(index) {
      this.selectedCouponList.splice(index, 1);
    },
    filterData() {},
    //搜索类型
    setType(val) {
      this.type = val.type;
      this.typeStr = val.title;
      this.toggle();
    },
    //优惠券保存
    couponSelectSure() {
      this.selectedCouponList = this.couponList.filter(item => item.check);
      this.type = "";
      this.dialogVisible = false;
    },
    //去重
    unique(a) {
      var ret = [];
      var hash = {};
      for (var i = 0, len = a.length; i < len; i++) {
        var item = a[i];
        var key = typeof item + item;
        if (hash[key] !== 1) {
          ret.push(item);
          hash[key] = 1;
        }
      }
      return ret;
    },
    //保存
    sure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          //活动奖品验证
          if (!this.addEditData.coupon && !this.addEditData.integral) {
            this.$message.error("请至少勾选一个活动奖品");
            return false;
          } else {
            if (this.addEditData.coupon) {
              if (!this.selectedCouponList.length) {
                this.$message.error("请选择优惠券");
                return false;
              }
            }
          }
          // 获取优惠券数据
          this.addEditData.coupons = [];
          this.selectedCouponList.forEach(item => {
            this.addEditData.coupons.push({
              id: item.id,
              num: item.num
            });
          });
          let data = {
            id: this.addEditData.id,
            type: this.addEditData.type,
            name: this.addEditData.name,
            timeScope: 1,
            userDay: this.addEditData.userDay ? 1 : 2,
            birthday: this.addEditData.birthday ? 1 : 2,
            startTime: this.addEditData.startEndTime[0],
            endTime: this.addEditData.startEndTime[1],
            rules: this.addEditData.rules,
            obj: parseInt(this.addEditData.obj),
            upObj: parseInt(this.addEditData.upObj),
            consume: this.addEditData.consume,
            coupon: this.addEditData.coupon ? 1 : 2,
            coupons: this.addEditData.coupons,
            integral: this.addEditData.integral ? 1 : 2,
            integralNum: this.addEditData.integralNum,
            integralDouble: this.addEditData.integralDouble
          };
          addEditActive(data).then(res => {
            if (!res.data.errCode) {
              this.$message({
                type: "success",
                message: this.addEditData.id ? "编辑成功" : "新增成功"
              });
              this.$router.push("/index/memberPrivilege");
            }
          });

          console.log("成功");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //获取编辑数据
    _getActiveInfo(id) {
      getActiveInfo({ id }).then(res => {
        let manageInfo = res.data.manageInfo;
        this.addEditData = {
          id: id,
          type: manageInfo.type,
          name: manageInfo.name,
          timeScope: 1,
          userDay: manageInfo.userDay == 1,
          birthday: manageInfo.birthday == 1,
          rules: manageInfo.rule,
          obj: parseInt(manageInfo.obj),
          upObj: parseInt(manageInfo.upObj),
          coupon: manageInfo.coupon == 1,
          coupons: [],
          integral: manageInfo.integral == 1,
          integralDouble: manageInfo.integralDouble + "",
          integralNum: manageInfo.integralNum
            ? manageInfo.integralNum
            : undefined,
          consume: manageInfo.consume,
          startEndTime: [manageInfo.startTime, manageInfo.endTime]
        };
        this.selectedCouponList = manageInfo.coupons;
        if (this.addEditData.rules.length == this.memberCardList.length) {
          this.checkAll = true;
        }
      });
    }
  },
  created() {
    let { type, id, view } = this.$route.query;
    this.addEditData.type = type;
    this.addEditData.id = id;
    this._getMemberCardList();
    if (id) {
      this._getActiveInfo(id);
    }
    if (view) {
      this.isLook = true;
    }

    this._getCouponList();
  },
  mounted() {}
};
</script>
<style lang="scss" scoped>
.add-edit {
  .el-radio {
    margin-left: 0;
    margin-right: 20px;
  }
  .box {
    & > h3 {
      margin: 15px 0;
      font-size: 16px;
      color: #6d2377;
    }
    & > div.box-1 {
      padding-left: 30px;
      margin-bottom: 30px;
      .name {
        padding-right: 20px;
        height: 34px;
        line-height: 34px;
      }
    }
  }
}
</style>